package com.offcn.oauth.controller;

import com.offcn.entity.Result;
import com.offcn.entity.StatusCode;
import com.offcn.oauth.entity.AuthToken;
import com.offcn.oauth.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/userOauth")
public class AuthController {

    @Value("${auth.clientId}")
    private String clientId;

    @Value("${auth.clientSecret}")
    private String clientSecret;

    @Autowired
    private AuthService authService;

    @PostMapping("/login")
    public Result<AuthToken> login(@RequestBody Map<String, String> map, HttpServletResponse response){
        AuthToken authToken = authService.login(map.get("username"), map.get("password"), clientId, clientSecret);
        Cookie cookie = new Cookie("Authorization", authToken.getAccessToken());
        cookie.setPath("/");
        response.addCookie(cookie);
        // 3秒钟之后 进行跳转到 之前访问的页面
        response.setHeader("Refresh","3;URL=http://localhost:8888" + map.get("from"));
        return new Result<>(true, StatusCode.OK,authToken,"登录成功");
    }


}
